package com.ruoyi.teaching.config;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.ssl.SSLContextBuilder;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.net.ssl.SSLContext;

/**
 * @author 15332
 * @version 1.0
 * @date 2025/9/9 15:51
 * @description TODO
 */
@Configuration
public class ElasticsearchConfig {

  @Value("${spring.elasticsearch.uris}")
  private String elasticsearchUri;

  @Value("${spring.elasticsearch.username}")
  private String username;

  @Value("${spring.elasticsearch.password}")
  private String password;

  @Bean
  public RestClient elasticsearchRestClient() throws Exception {
    // 创建信任所有证书的 SSL 上下文
    SSLContext sslContext = SSLContextBuilder
      .create()
      .loadTrustMaterial(null, (chain, authType) -> true)
      .build();

    // 设置认证信息
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(
      AuthScope.ANY,
      new UsernamePasswordCredentials(username, password)
    );

    return RestClient.builder(HttpHost.create(elasticsearchUri))
      .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder
        .setSSLContext(sslContext)
        .setSSLHostnameVerifier((hostname, session) -> true)
        .setDefaultCredentialsProvider(credentialsProvider)
        .setMaxConnTotal(100)
        .setMaxConnPerRoute(20))
      .build();
  }

  @Bean
  public ElasticsearchTransport elasticsearchTransport() throws Exception {
    return new RestClientTransport(
      elasticsearchRestClient(),
      new JacksonJsonpMapper()
    );
  }

  @Bean
  public ElasticsearchClient elasticsearchClient() throws Exception {
    return new ElasticsearchClient(elasticsearchTransport());
  }
}

